package com.chapter16.Synchronized;

/**
 * @author 宋鑫宇
 * @version 1.0
 */
public class Synchronized {
    public static void main(String[] args) {
        C1 c1 = new C1();
        Thread thread = new Thread(c1);
        Thread thread1 = new Thread(c1);
        Thread thread2 = new Thread(c1);
        thread.start();
        thread1.start();
        thread2.start();
    }
}

//实现Runnable接口，使用Synchronized实现线程同步
class C1 implements Runnable {
    public int i = 100;
    public static boolean loop = true;

    @Override
    public void run() {

        while (loop) {
            sell();
        }
    }

    /*
         1.public synchronized void sell(){}就是一个同步方法
         2.这时，锁在this对象
         3.也可以在代码块上写synchronized，同步代码块，互斥锁还是在this对象

         同步方法（静态的）的锁为当前类本身
          public synchronized static void m1(){}
         如果在静态方法中，同步一个代码块需要在 synchronized() 中加入 当前类.class
          public static void m2(){
                synchronized (C1.class){
                    System.out.println("m2");
                }
          }


    * */
    public synchronized static void m1(){}
    public static void m2(){
        synchronized (C1.class){
            System.out.println("m2");
        }
    }

    public synchronized void sell() {//在同一时刻只能有一个线程来执行run方法
        if (i <= 0) {
            loop = false;
            return;
        }
        System.out.println(--i + " " + Thread.currentThread().getName());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}
